<template>
  <el-card class="m-8">
    <section slot="header" class="flex items-center justify-center mb-10">
      <p class="">奖池选择：</p>
      <el-select v-model="listQuery.is_next" placeholder="请选择" class="mr-4">
        <el-option
          v-for="item in poolOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button type="primary" @click="handleChangeBox">确认切换</el-button>
    </section>


    <section slot="header" class="mb-4 flex items-center justify-between">
      <div>
        <el-button class="mr-4" type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleEditAll">批量编辑</el-button>
        <el-button v-if="listQuery.is_next === 0" type="danger" @click="handleReplace">替换新奖池</el-button>
      </div>
      <div>
        <el-radio-group v-model="listQuery.level" @input="handleChangeBox">
          <el-radio-button :label="1">初级宝箱</el-radio-button>
          <el-radio-button :label="2">中级宝箱</el-radio-button>
          <el-radio-button :label="3">高级宝箱</el-radio-button>
        </el-radio-group>
      </div>
    </section>

    <el-table :data="tableList" align="center" border class="mt-4" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="奖励名称" prop="detail.name"/>
      <el-table-column label="奖励类型" prop="reward_type">
        <template slot-scope="scoped">
          {{ scoped.row.reward_type === 'gift' ? '礼物' : scoped.row.reward_type === 'product'? '装扮' : '碎片' }}
        </template>
      </el-table-column>
      <el-table-column label="奖励价值（m豆）" prop="price">
        <template slot-scope="{row}">
          {{ row.reward_type === 'gift' ? row.price: '--' }}
        </template>
      </el-table-column>
      <el-table-column label="有效期（天）" prop="count">
        <template slot-scope="{row}">
          {{ row.reward_type === 'product' ? row.count: '--' }}
        </template>
      </el-table-column>
      <el-table-column label="礼物图案" prop="picture">
        <template slot-scope="scoped">
          <el-popover max-width="420" placement="right" trigger="hover">
            <img :lazy="true" :src="scoped.row.detail.picture" class="imageStyle" fit="fill" />
            <img
              slot="reference"
              :src="scoped.row.detail.picture"
              alt=""
              style="width: 80px"
            />
          </el-popover>
          
        </template>
      </el-table-column>
      <el-table-column label="权重" prop="number"/>
      <el-table-column label="添加时间" prop="created_at"/>

      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="{row}">
          <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <cus-pagination
      :limit.sync="listQuery.perPage"
      :page.sync="listQuery.page"
      :total="total"
      @pagination="initData"
    />

    <el-dialog
      :title="isEdit?'编辑':'新增'"
      :visible.sync="addDialog2"
      lock-scroll
      width="30%"
      @close="closeAddDialog2"
    >
      <el-form ref="form" :inline="false" :model="form" :rules="rules" label-width="150px" size="normal">
        <el-form-item v-if="!isEdit" label="奖励类型" prop="reward_type">
          <el-select v-model="form.reward_type" clearable filterable placeholder="请选择奖励类型" @change=handleChange>
            <el-option
              v-for="item in rewardType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="isEdit?'选择替换奖励':'选择奖励'" prop="reward_id">
          <el-select
            v-model="form.reward_id"
            v-if="form.reward_type === 'gift'"
            filterable
            remote
            clearable
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            @clear="handelClear"
            :loading="loading2">
              <el-option v-for="item in options2"
                :key="item.reward_id"
                :label="item.name"
                :value="item.reward_id">
                <el-popover placement="right" trigger="hover">
                  <img :src="item.picture" alt="" style="max-width: 200px;max-height: 200px">
                  <p slot="reference">{{ item.name }}({{item.price + 'M豆'}})</p>
                </el-popover>
              </el-option>
          </el-select>
          <el-select
            v-model="form.reward_id"
            v-if="form.reward_type === 'product'"
            filterable
            remote
            clearable
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            @clear="handelClear"
            :loading="loading2">
                <el-option v-for="item in options4"
                    :key="item.reward_id"
                    :label="item.name"
                    :value="item.reward_id">
                </el-option>
        </el-select>
        </el-form-item>

        <el-form-item label="数量/权重" prop="number">
          <el-input type="number" v-model.number="form.number"  @input="handleInput3"></el-input>
        </el-form-item>
        
        <el-form-item v-if="form.reward_type === 'product'" label="奖励有效期" prop="count">
          <el-input type="number" v-model.number="form.count"  @input="handleInput2">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
      </el-form>

      <section slot="footer">
        <el-button @click="addDialog2 = false">取消</el-button>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </section>
    </el-dialog>

    <el-dialog
      :visible.sync="editAllDialogVisible"
      title="批量编辑"
      width="435px"
    >
      <p class="mb-4">提示：您已选择 {{ this.titleList.toString() }} 等......多条数据</p>
      <div class="flex items-center" style="text-wrap: nowrap;">
        <p><span style="color: red">*</span>修改奖励权重：</p>
        <el-input type="number" v-model="number" @input="handleInput4"></el-input>
      </div>

      <span slot="footer" class="dialog-footer">
            <el-button @click="editAllDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmEditAll">确 定</el-button>
        </span>
    </el-dialog>
  </el-card>


</template>

<script>
import { 
  rechargeRewardList, 
  rechargeRewardAdd, 
  rechargeRewardEdit,
  rechargeRewardBatch,
  rechargeRewardReplace, 
  rechargeRewardLog,
  rechargeRewardDel
} from '@/api/dailyFirstRecharge'
import {
  // 奖励列表
  listData
} from '@/api/sunGame/sunGame'
import { getData } from '@/api/roomGift/giftList'
import { productList } from '@/api/petsManagement'

export default {
  data() {
    return {
      loading2: false,
      radio1: 1,
      poolOptions: [
        {
          value: 0,
          label: '本期奖池'
        },
        {
          value: 1,
          label: '下期奖池'
        }
      ],
      rewardType: [
        {
          value: 'gift',
          label: '礼物'
        },
        {
          value: 'product',
          label: '装扮'
        },
        // {
        //   value:'debris',
        //   label: '碎片'
        // }
      ],
      options2: [],
      options3: [],
      options4: [],
      selectData: '',
      menuList: [],
      tableList: [],
      user_code: '',
      nickname: '',
      dateList: undefined,
      listQuery: {
        page: 1,
        perPage: 10,
        type: 2, //1:普通奖励配置 2:限定奖励配置
        is_next: 0, //0:本期奖池 1:下期奖池
        level: 1, //1初2中3高级
      },
      meta: {
        page: 1,
        perPage: 10

      },
      total: 0,
      /* 弹出框开关 */
      addDialog: false,
      addDialog2: false,

      rejectLoading: false,
      passLoading: false,
      id: '',
      // 拒绝原因
      reject_reason: '',
      form: {
        id: undefined,
        reward_id: undefined,
        count: undefined,
        reward_type: undefined,
        number: undefined
      },
      rules: {
        reward_id: [{ required: true, message: '请选择奖励', trigger: 'blur' }],
        reward_type: [{ required: true, message: '请选择奖励类型', trigger: 'blur' }],
        number: [{ required: true, message: '请输入获奖概率', trigger: 'blur' }],
        count: [{ required: true, message: '请输入获奖概率', trigger: 'blur' }]
      },
      multipleSelection: [],
      dataIds: '',
      number: '',
      editAllDialogVisible: false,
      isEdit: false,
      titleList: [],
      query: undefined
    }
  },
  created() {
    this.initData()
    this.handleGetGiftData()
    this.getProductList()
  },
  methods: {
    handleGetGiftData() {
        getData({
            gift_name: this.query,
            page: 1,
            page_size: 20
        }).then(res => {
            res.data.data.map(item => {
                item.reward_id = item.id
            })
            this.options2 = res.data.data
        })
    },
    getProductList() {
        productList({
            name: this.query,
            cate_id: 0,
            style_id: 0,
            status: 1,
            page: 1,
            page_size: 20
        }).then(res => {
            res.data.data.map(item => {
                item.name = item.product_name
                item.reward_id = item.id
            })
            this.options4 = res.data.data
        })
    },
    handleChange(val) {
      this.form.reward_id = undefined
      this.query = undefined
      if(this.form.reward_type === 'gift') {
          this.handleGetGiftData()
      }
      if(this.form.reward_type === 'product') {
          this.getProductList()
      }
    },
    confirmEditAll() {
      if (!this.number) {
        this.$message({
          message: '输入正确的值',
          type: 'warning'
        })
      } else {
        rechargeRewardBatch({
          ids: this.dataIds.toString(),
          number: this.number,
          is_next: this.listQuery.is_next,
          type:  this.listQuery.type
        }).then(res => {
          if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
              this.editAllDialogVisible = false
              this.initData()
        })
      }
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击批量删除
    handleEditAll() {
      if (this.multipleSelection.length < 2) {
        this.$message({
          message: '请选择2条或2条以上的内容',
          type: 'warning'
        })
        return
      } else {
        
        let ids = []
        this.titleList = []
        for (let key in this.multipleSelection) {
          if(key < 3) {
            this.titleList.push(this.multipleSelection[key].detail.name)
          }
          // ids += `${this.multipleSelection[key].id},`
          ids.push(this.multipleSelection[key].id)
        }
        // ids = ids.substring(0, ids.length - 1)
        this.dataIds = ids
      }
      this.editAllDialogVisible = true
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.isEdit = true
      this.addDialog2 = true
      this.query = this.form.detail.name
      if (this.query !== '') {
          if(this.form.reward_type === 'gift') {
              this.handleGetGiftData()
          }
          if(this.form.reward_type === 'product') {
              this.getProductList()
          }
      }
    },
    handleAdd() {
      this.isEdit = false
      this.addDialog2 = true
    },
    handleReplace() {
      this.$confirm('确认替换奖池?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        rechargeRewardReplace({
          type: 2
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
          this.initData()
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      
    },
    handleSearch() {
      this.listQuery.page = 1
      this.initData()
    },
    handleChangeBox() {
      this.initData()
    },
    async initData() {
      try {
        for (let key in this.listQuery) {
          this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key]
        }
        const { data } = await rechargeRewardList(this.listQuery)
        this.total = data.meta.total
        this.tableList = data.list
        
      } catch (e) {
        console.error(e)
      }
    },

    handleDelete(row) {
      this.$confirm('此操作不可恢复，是否继续删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const { code, data } = await rechargeRewardDel({
          id: row.id,
          type: 2,
          is_next: this.listQuery.is_next
        })
        if (code === 200) {

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.initData()
        }
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    async handleChecked() {
      if (!this.user_code.trim()) {
        return void this.$message.warning('请填写用户编号！')
      }
      let data = {
        id: this.user_code,
        page: 1
      }
      giftList(data).then(res => {
        if (res.data) {
          this.addDialog = false
          this.addDialog2 = true
          this.form.gift_id = res.data.data[0].id
          this.form.name = res.data.data[0].name
          this.form.price = res.data.data[0].price
        }
      }).finally(() => this.rejectLoading = false)
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {

          for (let key in this.form) {
            this.form[key] = !this.form[key] ? undefined : this.form[key]
          }
          this.form.type = this.listQuery.type
          this.form.is_next = this.listQuery.is_next
          this.form.level = this.listQuery.level
          if (this.form.id) {
            rechargeRewardEdit(this.form).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
                this.addDialog2 = false
                this.initData()
              }
            })
          } else {
            rechargeRewardAdd(this.form).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
                this.addDialog2 = false
                this.initData()
              }
            })
          }

        }
      })
    },
    closeAddDialog() {
      this.user_code = undefined
    },
    closeAddDialog2() {
      if (this.$refs['form']) {
        this.$refs['form'].clearValidate() // 清除整个表单的校验
        this.$refs['form'].resetFields() // 清除整个表单的校验
      }
      this.form = {
        id: undefined,
        reward_id: undefined,
        count: undefined,
        reward_type: undefined,
        number: undefined
      }
    },
    handleInput(val) {
      if(val < 1) {
        this.form.stock = undefined
      }
      if(val.includes('.')) {
        this.form.stock = val.replace('.', '')
      }
    },
    handleInput2(val) {
      if(val < 1) {
        this.form.sort = undefined
      }
      if(val.includes('.')) {
        this.form.sort = val.replace('.', '')
      }
    },
    handleInput3(val) {
      console.log(typeof val)
      if(val < 0) {
        this.form.rate = undefined
      }
      // if(val.includes('.')) {
      //   this.form.rate = val.replace('.', '')
      // }
    },
    handleInput4(val) {
      if(val < 1) {
        this.number = undefined
      }
      if(val.includes('.')) {
        this.number = val.replace('.', '')
      }
    },
    remoteMethod(query) {
        this.query = query
        if (query !== '') {
            if(this.form.reward_type === 'gift') {
                this.handleGetGiftData()
            }
            if(this.form.reward_type === 'product') {
                this.getProductList()
            }
        }
    },
    handelClear() {
        this.query = undefined
        if(this.form.reward_type === 'gift') {
            this.handleGetGiftData()
        }
        if(this.form.reward_type === 'product') {
            this.getProductList()
        }
    }
  }
}
</script>

<style scoped>
.imageStyle {
  width: 250px;
}

.input {
  width: 200px;
}
</style>
